﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZBJF.Warranty.BLL.Cached;
using ZBJF.Warranty.Common.Common;
using ZBJF.Warranty.Model;
using ZBJF.Warranty.Model.CommonObject.PinanAPIEntity;
using ZBJF.Warranty.PinanAPI.Model;

namespace ZBJF.Warranty.PinanAPI
{
    public class InsuranceService
    {
        public static void ApplyPolicy(InsuranceOrder entity)
        {
            //1.从数据库获取Token
            //2.提交投保
            //3.根据结果 如果是Token过期，需要再次获取Token 再调用方法
            var appConfig = AppConfigCached.GetAppConfig();
            var caller = new WebApiCaller();
            var data = new InsuranceInfo
            {
                partnerName=appConfig.PinanClientID,
                departmentCode="",
                applicantInfo = new ApplicantInfo
                {
                    name = entity.UserName,
                    certificateNo=entity.CertificateNO,
                    certificateType = "01"
                },
                productInfoList = new List<ProductInfo>
                {
                    new ProductInfo
                    {
                        baseInfo= new ProductBaseInfo
                        {
                            insuranceBeginDate="",
                            insuranceEndDate="",
                            productCode="",
                            transactionNo="",
                            totalActualPremium="",
                        },
                    }
                }
            };
            var json =
                caller.Get(
                    string.Format(
                        appConfig.PinanAPIUrl.TrimEnd('/') +
                        "/open/appsvr/property/standardApplyPolicyRiskPropertyNoPay?access_token={0}&request_id={1}",
                        appConfig.PinanAssessToken, "standardApplyPolicyRiskPropertyNoPay" + DateTime.Now),
                    JSON.Encode(data));

        }

        private static bool ValidateSelfServerCard(string carNo, string password, ref PinanValidateCardData resObj, bool indentityLogin = true)
        {
            #region 自助卡 返回示例
            /*
             {"ret":"0","msg":"","requestId":"open/appsvr/property/outerToPingAnPackage20171210231304","data":"{"insuranceClause":"cardDefine/13129/20170807114987781.htm","endAge":"65","catalog":{"A92":"A92","CTLIST_CB001":"CTLIST_CB001"},"policyRule":" 1、本保险不承保曲面屏幕、翻盖屏幕手机及IPAD类等大屏幕电子设备。<br>\r\n2、本保单每一被保险人限购1份，且在投保日期的第二天零时生效，保险期限1年。<br>\r\n3、在本保单有效期限内，请勿私自拆装投保手机、破坏螺丝封条、刷机，否则将不予理赔。<br>\r\n4、本保险不提供上门维修换屏服务，若您投保的手机屏幕破碎，需寄送或送达平安合作的维修网点，现场查勘后手机螺丝封条未被撕毁且不属于其他不予赔付的情形的，方可进行维修换屏。<br>\r\n\r\n5、保险期限：本保险的期限为1年，自投保人激活时选择的保险起期当日零时起生效，至约定的终止日二十四时止。<br>\r\n6、告知义务：依据《中华人民共和国保险法》的规定，投保人、被保险人应如实告知，否则保险人有权依法解除保险合同，并对于保险合同解除前发生的保险事故不负任何责任。投保人在投保时，应对投保书内各项内容如实详细地说明并填写清楚。否则，保险人有权依法解除保险合同。<br>\r\n7、保险凭证：中国平安财产保险公司对本卡投保的保险仅提供电子保单<br>\r\n8、保险人承保：本保险合同自投保人按保险生效流程投保并经保险公司审核同意承保方成立。<br>\r\n9、 本保险卡不挂失，请妥善保管。投保生效后，不办理退保、加保及被保险人信息的变更等保单批改。<br>\r\n","callId":"propInsuActiveService","password":"952203","cardNo":"0113129000000990","specialConditions":"无特别预定","waitDays":"0","coverage":"本卡保障期限为1年，保额1000元，保险范围包含：被保险手机在正常使用过程中，因跌落、挤压、碰撞等意外事故导致的屏幕破碎，对于被保险人在保单载明的维修机构维修屏幕时产生的维修费用，保险人按照本保险合同的约定负责赔偿。","cardTypeName":"新一代个财A92","policyPeriodUnit":"2","productPrompt":" 1、因本保险仅提供电子保单，您也可以在支付宝-保险服务-我的中查询保单信息。<br>2、本卡仅供投保使用，非保险凭证，您须在该卡的有效期内按保险流程进行投保，保险责任于您投保30日后零时开始生效。对保险责任生效前所发生的保险事故本公司不负给付保险金责任。<br>3、投保前请详细阅读保险条款及投保规则。","beginAge":"18","policyPeriod":"1","operType":"logonSics"}"}
             */
            #endregion
            var appConfig = AppConfigCached.GetAppConfig();
            var obj = new
            {
                partnerCode = "P_SPXZZK_PE",//appConfig.PinanClientID,
                tranCode = "keyPointspxInfo",
                OPEN_SERVICE_REQUEST = new
                {
                    operType = "logonSics",
                    cardNo = carNo.Trim(),
                    password = password.Trim(),
                    callId = "propInsuActiveService"
                }
            };
            var url = string.Format("{0}/open/appsvr/property/outerToPingAn?access_token={1}&request_id={2}",
                appConfig.PinanAPIUrl.TrimEnd('/'), appConfig.PinanAssessToken,
                "open/appsvr/property/outerToPingAn" + DateTime.Now.ToString("yyyyMMddHHmmss"));
            var json = new WebApiCaller().Post(url, JSON.Encode(obj));
            //{"data":"","msg":"已失效的access_token:14E255E7CF394AF7BD7C9278E887E9ABq","requestId":"open/appsvr/property/outerToPingAn20171228111832","ret":"13012"}

            CommonMethod.WriteLogs(json);
            var entity = (PinanIndentityReturnEntity)JSON.Decode(json, (typeof(PinanIndentityReturnEntity)));
            //resObj = entity;
            if (entity != null && entity.ret!=null)
            {
                if ((entity.ret == "13012" || entity.ret == "13005") && indentityLogin)
                {
                    PinanIdentityService.RefreshPinanToken();
                    return ValidateSelfServerCard(carNo, password, ref resObj, false);
                }
            }
            else
            {
                var retObj = (PinanValidateCardData)JSON.Decode(json, typeof(PinanValidateCardData));
                resObj = retObj;
                if (retObj != null && string.IsNullOrEmpty(retObj.errorMsg))
                {
                    return true;
                }
            }
            return false;
        }

        /// <summary>
        /// 验证 自助卡 
        /// </summary>
        /// <param name="carNo">卡号</param>
        /// <param name="password">密码</param>
        /// <param name="msg"></param>
        public static bool ValidateSelfServerCard(string carNo, string password, ref PinanValidateCardData resObj)
        {
            return ValidateSelfServerCard(carNo, password, ref resObj, true);
        }

        private static bool CreatePolicyByCard(ref InsuranceOrder order, ref string msg, bool indentityLogin = true)
        {
            var appConfig = AppConfigCached.GetAppConfig();
            var obj = new
            {
                partnerCode = "P_SPXZZK_PE",//appConfig.PinanClientID,
                tranCode = "keyPointspxInfo",
                OPEN_SERVICE_REQUEST = new
                {
                    operType = "activeSics",
                    cardNo = order.CardNo,
                    password = order.CardPwd,

                    callId = "P_ZBJFTEST",//"ZBJF-InsuranceOrder",


                    holderName = order.UserName,
                    holderSex = CommonMethod.GetSexByIndentityNo(order.CertificateNO),//"M",
                    holderBirthday = CommonMethod.GetBirthdayByIndentityNo(order.CertificateNO),//"1999-10-30",
                    holderIdNo = order.CertificateNO,//"321322199910301817",
                    holderIdType = "01",
                    holderBloodtype = "e",//e>为自己投保；c>为他人投保
                    holderMobile = order.UserPhone,
                    isFillHolderMobile = "123456",
                    holderEmail = "zbjf@qq.com",
                    isFillHolderEmail = "0111738000000000",

                    callName = "中保金服-保单系统",
                    relatedKey = order.ID,

                    name = order.UserName,
                    channel = "11",
                    sex = CommonMethod.GetSexByIndentityNo(order.CertificateNO),
                    birthday = CommonMethod.GetBirthdayByIndentityNo(order.CertificateNO),
                    idNo = order.CertificateNO,
                    idType = "01",
                    mobile = order.UserPhone,
                    email = "zbjf@qq.com",

                    mobilePhoneBrand=order.ProductBrandName,
                    mobilePhoneModel=order.ProductModelName,
                    mobilePhoneIMEI = order.IMEI,
                    //postCode="",
                    //beginDate="",

                    address = "address",
                    petType = "123456",
                    petBreed = "0111738000000000",
                    petAge = "28",
                    petHairColour = "Black",
                    identityNo = order.CertificateNO,
                    petName = order.UserName,
                    petSex = CommonMethod.GetSexByIndentityNo(order.CertificateNO)
                }
            };
            var url = string.Format("{0}/open/appsvr/property/outerToPingAn?access_token={1}&request_id={2}", appConfig.PinanAPIUrl.TrimEnd('/'), appConfig.PinanAssessToken, "/appsvr/property/outerToPingAn" + DateTime.Now.ToString("yyyyMMddHHmmss"));
            var body = JSON.Encode(obj);
            CommonMethod.WriteLogs(string.Format("URL:{0},BODY:{1}", url, body));
            var json = new WebApiCaller().Post(url, body);

            CommonMethod.WriteLogs(json);

            var entity = (PinanIndentityReturnEntity)JSON.Decode(json, (typeof(PinanIndentityReturnEntity)));
            //resObj = entity;
            if (entity != null && entity.ret!=null)
            {
                if ((entity.ret == "13012" || entity.ret == "13005") && indentityLogin)
                {
                    PinanIdentityService.RefreshPinanToken();
                    return CreatePolicyByCard(ref order, ref msg, false);
                }
            }
            else
            {
                var ht = JSON.Decode(json) as Hashtable;
                if (ht != null)
                {
                    if (ht["policyNo"] != null && ht["effDate"] != null && ht["matuDate"] != null)
                    {
                        order.Effective = true;
                        order.ThirdUniqueNumber = ht["policyNo"].ToString();
                        order.ThirdOrderNO = ht["policyNo"].ToString();
                        order.EffectiveDate = CommonMethod.ConvertToDateTime(ht["effDate"].ToString());
                        order.ServiceStartTime = order.EffectiveDate;
                        order.ServiceEndTime = CommonMethod.ConvertToDateTime(ht["matuDate"].ToString());

                        return true;
                    }
                    if (ht["errorMsg"] != null)
                    {
                        msg = ht["errorMsg"].ToString();
                    }
                }
                else
                {
                    msg = "json is null";
                }
                return false;
            }
            return false;
        }
        /// <summary>
        /// 根据自助卡  投保
        /// </summary>
        public static bool CreatePolicyByCard(ref InsuranceOrder order,ref string msg)
        {
            return CreatePolicyByCard(ref order, ref msg, true);
        }

    }
}
